Skip to main content

Experiments

What Happens When You Try to Index Into An Array With a Float?

In JavaScript, when you attempt to access an array element using a floating-point number as an index, the number is converted to a string and the array is treated as an object. In JavaScript, array indices are essentially treated as object keys, and all object keys are strings. This can lead to unexpected behavior compared to languages that strictly enforce integer indices for arrays.

Here's what happens:

  1. Conversion to String: The floating-point number is converted to a string. For example, an index of 2.5 becomes "2.5".

  2. Accessing as an Object Property: The array is then accessed with this string key. Since normal arrays do not have a property with such a string key, the result will be undefined.

  3. No Array Bounds Error: Unlike some other languages, JavaScript doesn't throw an error if you access an array with an out-of-bounds index (whether it's a floating point or an integer). It simply returns undefined.

let arr = [1, 2, 3];
console.log(arr[2.5]); // undefined

This behavior underscores the importance of being cautious with arithmetic that could result in non-integer values when calculating indices.